package com.gym.core.monitor.aop;

import java.lang.reflect.Method;

import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;

import com.gym.core.monitor.PerformanceMonitor;

/**
 * 性能监控日志
 * @author xinchun.wang
   @email: 532002108@qq.com
 * @createTime 2015-8-28 下午9:26:54
 */
@Aspect
@Order(10)
public class PerformanceMonitorAspect {
	private  static Logger logger = LoggerFactory.getLogger(PerformanceMonitorAspect.class);

    @Around("@annotation(com.gym.core.monitor.PerformanceMonitor)")
    public Object performanceMonitor(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();

        PerformanceMonitor annotation = method.getAnnotation(PerformanceMonitor.class);
        if (annotation == null) {
            return pjp.proceed(pjp.getArgs());
        }
        String monitorName = getMonitorName(annotation, method);
        long start = System.currentTimeMillis();
        try {
            Object result = pjp.proceed(pjp.getArgs());
            logger.info(monitorName,System.currentTimeMillis()-start);
            return result;
        } catch (Throwable throwable) {
        	 logger.info(monitorName,System.currentTimeMillis()-start);
            throw throwable;
        }
    }

    private String getMonitorName(PerformanceMonitor annotation, Method method) {
        String monitorName = StringUtils.isNotBlank(annotation.value()) ? annotation.value() : method.getName();
        if(annotation.joinClassName()){
            monitorName = method.getDeclaringClass().getSimpleName() + "_" + monitorName;
        }
        return monitorName;
    }
}
